package com.cangsan.erhai.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cangsan.erhai.common.PageBean;
import com.cangsan.erhai.common.R;
import com.cangsan.erhai.entity.SysUser;
import com.cangsan.erhai.entity.SysUserRole;
import com.cangsan.erhai.service.SysUserRoleService;
import com.cangsan.erhai.service.SysUserService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/user")
public class SysUserController {
    @Value("${upload.baseDir}")
    private  String uploadBasedir;
    @Autowired
    private  SysUserService userService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @PostMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("user_name",pageBean.getQuery());
        Page<SysUser> page = new Page<>(pageBean.getPageNum(), pageBean.getPageSize());

        Page<SysUser> pageResult = userService.page(page,queryWrapper);
        Map<String,Object>  result = new HashMap<>();
        List<SysUser> records = pageResult.getRecords();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        result.put("userList",records);
        result.put("total",pageResult.getTotal());
        return R.ok(result);

    }




    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file) throws IOException {
        Map<String,Object> resultMap = new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename = file.getOriginalFilename();
            String suffinxName = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName = DateUtil.format(new Date(),"yyyy-MM-dd")+suffinxName;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(uploadBasedir,newFileName));
            resultMap.put("code",0);
            resultMap.put("msg","上传成");
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","files/"+newFileName);
            resultMap.put("data",dataMap);
        }
        return resultMap;
    }


    @PostMapping("/saveOrUpdate")
    public R saveOrUpdate(@RequestBody SysUser sysUser){
        if(Objects.isNull(sysUser.getUserId())){
            String userName = sysUser.getUserName();
            LambdaQueryWrapper<SysUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(SysUser::getUserName,userName);
            List<SysUser> list = userService.list(lqw);
            if(!CollectionUtil.isEmpty(list)){
                return R.fail("用户名已经存在");
            }
        }
        String password = sysUser.getPassword();
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(password);
        sysUser.setPassword(encode);
        userService.saveOrUpdate(sysUser);
        return R.ok();
    }

    @PostMapping("/wxSaveOrUpdate")
    public R wxSaveOrUpdate(@RequestBody SysUser sysUser){

        userService.saveOrUpdate(sysUser);
        return R.ok();
    }

    @GetMapping("/getRoleByUserId/{userId}")
    public R getRoleByUserId(@PathVariable("userId") Long userId){
        return R.ok( sysUserRoleService.roleByUserId(userId));
    }





    @PostMapping("/addRole")
    public R addRole(@RequestBody JSONObject object){
        Long userId = object.getLong("userId");
        JSONArray userRoleArr = object.getJSONArray("userRole");
        List<SysUserRole> userRoles = new ArrayList<>();
        for (int i = 0; i < userRoleArr.size(); i++) {
            JSONObject jsonObject = userRoleArr.getJSONObject(i);
            Long roleId = jsonObject.getLong("roleId");
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            userRoles.add(sysUserRole);
        }
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<SysUserRole>();
        LambdaQueryWrapper<SysUserRole> eq = wrapper.eq(SysUserRole::getUserId, userId);
        sysUserRoleService.remove(eq);
        sysUserRoleService.saveBatch(userRoles);
        return R.ok();
    }

    @GetMapping("/{id}")
    public R deleteUser(@PathVariable Long id) {
        sysUserRoleService.removeById(id);
        return R.ok("删除成功");
    }

}
